package com.atguigu.lease.web.app.custom.interceptor;

import com.atguigu.lease.common.utils.JwtUtil;
import com.atguigu.lease.model.login.LoginUser;
import com.atguigu.lease.model.login.LoginUserHolder;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class AuthenticationInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String accessToken = request.getHeader("access-token");
        Claims claims = JwtUtil.parseJwt(accessToken);
        LoginUser loginUser = new LoginUser(claims.get("phone", String.class), claims.get("userId", Long.class));
        LoginUserHolder.setThreadLocal(loginUser);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        LoginUserHolder.clear();
    }
}
